package cn.lili.modules.payment.entity.dos;

import cn.lili.common.enums.ResultCode;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.utils.StringUtils;
import cn.lili.mybatis.model.BaseEntity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.*;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * 退款日志
 *
 * @author Chopper
 * @since 2021/1/28 09:21
 */
@Data
@TableName("li_refund_log")
@Builder
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "退款日志")
@EqualsAndHashCode(callSuper = true)
public class RefundLog extends BaseEntity {

    private static final long serialVersionUID = 3206432601756442476L;

    @ApiModelProperty(value = "用户ID")
    private String userId;

    @ApiModelProperty(value = "订单编号")
    private String orderSn;

    @ApiModelProperty(value = "退单编号")
    private String afterSaleNo;

    @ApiModelProperty(value = "退款金额")
    private Double price;

    @ApiModelProperty(value = "该笔交易实际支付金额")
    private Double payPrice;

    @ApiModelProperty(value = "是否已退款")
    private Boolean isRefund;

    @ApiModelProperty(value = "退款方式")
    private String paymentMethod;

    @ApiModelProperty(value = "第三方支付发起交易号")
    private String outTradeNo;

    @ApiModelProperty(value = "第三方平台付款流水号")
    private String transactionId;


    @ApiModelProperty(value = "第三方退款请求流水")
    private String outRefundNo;

    @ApiModelProperty(value = "第三方平台退款流水号")
    private String refundTransactionId;

    @ApiModelProperty(value = "退款理由")
    private String refundReason;

    @ApiModelProperty(value = "退款失败原因")
    private String errorMessage;


    @ApiModelProperty(value = "商户ID")
    private String mchId;

    @CreatedDate
    @JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @TableField(fill = FieldFill.INSERT)
    @ApiModelProperty(value = "创建时间", hidden = true)
    private Date createTime;

    public Double getPrice() {
        if (price == null || price <= 0 || price > payPrice) {
            throw new ServiceException(ResultCode.AFTER_STATUS_ERROR, "退款金额错误");
        }
        return price;
    }


    public String generateRefundDescription() {
        return String.format("订单[%s]退款[%s]元", orderSn, StringUtils.formatPrice(price));
    }

}